<template>
  <w-modal
    ref="WModal"
    title="文字识别(网络图片)"
    :ok-text="identifyArr.length ? '清除' : '识别'"
    :ok-type="identifyArr.length > 0 ? 'danger' : 'primary'"
    @ok="okClick"
  >
    <div v-if="identifyArr.length">
      <p v-for="(v, k) in identifyArr" :key="k">
        {{ v.words }}
      </p>
    </div>
    <a-input v-show="!identifyArr.length" v-model="upImageSrc" type="textarea" placeholder="请输入图片链接" />
  </w-modal>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Api } from '@/config/api'
import WModal, { ModalComType } from '@/components/global/modal'

@Component({
  name: 'WebToolImageIdentifyTextUrl',
  components: {
    WModal
  }
})
export default class WebToolImageIdentifyTextUrl extends Vue {
  // 识别出的文字
  identifyArr = [];
  // 上传文件图片路径
  upImageSrc = '';
  // 清除数据
  clearData () {
    this.upImageSrc = ''
    this.identifyArr = []
  }

  // 图片识别按钮点击
  imageInentifyBtnClick () {
    if (!this.upImageSrc) {
      this.$message.error('请输入图片链接')
      return
    }
    (this.$refs.WModal as ModalComType).showLoading()
    this.$wAxios
      .$post(Api.baidu.urlTextIdentify, {
        url: this.upImageSrc
      })
      .then((data) => {
        if (data.words_result && data.words_result.length > 0) {
          this.identifyArr = data.words_result
        } else {
          this.$message.error('没有识别出文字')
        }
      })
      .catch(() => {
        this.identifyArr = []
      })
      .finally(() => {
        (this.$refs.WModal as ModalComType).hideLoading()
      })
  }

  okClick () {
    if (this.identifyArr.length) {
      this.clearData()
    } else {
      this.imageInentifyBtnClick()
    }
  }

  /**
   * 显示弹窗
   */
  show () {
    (this.$refs.WModal as ModalComType).show()
  }
}
</script>

<style scoped></style>
